package com.lin.java.tool.mybatis.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.lin.java.tool.common.model.DataPage;
import com.lin.java.tool.common.model.QueryPage;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: linjiang
 * @date: 2024/12/17
 */
public class QueryPageUtil {

    public static <E, T> DataPage lambdaPageQuery(IService<E> service, QueryPage queryPage, Consumer<LambdaQueryWrapper<E>> queryCondition, Function<E, T> resultHandler) {
        LambdaQueryWrapper<E> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryCondition.accept(lambdaQueryWrapper);
        return pageQuery(service, queryPage, lambdaQueryWrapper, resultHandler);
    }

    public static <E, T> DataPage pageQuery(IService<E> service, QueryPage queryPage, LambdaQueryWrapper<E> lambdaQueryWrapper, Function<E, T> resultHandler) {
        Page<E> page = new Page<>(queryPage.getPageNum(), queryPage.getPageSize());
        Page<E> resultPage = service.page(page, lambdaQueryWrapper);
        // 记录数
        List<T> data = resultPage.getRecords().stream().map(resultHandler).collect(Collectors.toList());
        return DataPage.<T>builder().data(data)
                .pageNum(resultPage.getCurrent())
                .pageSize(resultPage.getSize())
                .total(resultPage.getTotal())
                .build();
    }

    /**
     * 转换分页对象
     *
     * @param page          分页数据对象
     * @param resultHandler 结果集处理
     * @return
     */
    public static <T, C> DataPage<C> convertPage(Page<T> page, Function<T, C> resultHandler) {
        List<C> data = page.getRecords().stream().map(resultHandler).collect(Collectors.toList());
        return DataPage.<C>builder().data(data)
                .pageNum(page.getCurrent())
                .pageSize(page.getSize())
                .total(page.getTotal())
                .build();
    }
}
